<template>
  <div id="userLoginPage">
    <h2 class="title">果图图云图库 - 用户登录</h2>
    <div class="desc">企业级智能协同云图库</div>
    <a-form :model="formState" autocomplete="off" @finish="handleSubmit">
      <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号' }]">
        <a-input v-model:value="formState.userAccount" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item
        name="userPassword"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 8, message: '密码不能小于八位' },
        ]"
      >
        <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码" />
      </a-form-item>
      <div class="tips">
        没有账号？
        <RouterLink to="/user/register">去注册</RouterLink>
      </div>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue'
import { userLoginUsingPost } from '@/api/userController.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStores.ts'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'

/**
 * 用于接收用户登录表单输入的值
 */
const formState = reactive<API.UserLoginRequest>({
  userAccount: '',
  userPassword: '',
})

// 引入全局状态管理器
const loginUserState = useLoginUserStore()

const router = useRouter()
const route = useRoute()

/**
 * 提交表单进行登录
 * @param values
 */
const handleSubmit = async (values: any) => {
  const res = await userLoginUsingPost(values)
  if (res.data.code === 0 && res.data.data) {
    // 登录成功，把登录态保存到全局状态中
    await loginUserState.fetchLoginUser()
    message.success('登录成功')
    // 取出重定向信息，如果为空，默认重定向到首页
    const urlParams = new URLSearchParams(window.location.search);
    const redirectUrl = urlParams.get("redirect") || "/";
    if(redirectUrl.includes('/picture')) {
      // 在新标签页打开重定向页面
      window.open(redirectUrl, '_blank');
      // 将当前页面重定向到主页并替换历史记录
      window.location.replace('/');
    } else {
      window.location.replace(redirectUrl);
    }
  } else {
    message.error('登录失败，' + res.data.message)
  }
}
</script>

<style scoped>
#userLoginPage {
  max-width: 360px;
  margin: 0 auto;
}

.title {
  text-align: center;
  margin-bottom: 16px;
}

.desc {
  color: #aaa;
  text-align: center;
  margin-bottom: 16px;
}

.tips {
  color: #bbb;
  text-align: right;
  font-size: 13px;
  margin-bottom: 16px;
}
</style>
